package com.macro.mall.portal.wxpay.helper;

import com.macro.mall.portal.util.MyCodeUtil;
import com.macro.mall.portal.wxpay.domain.vo.CreateOrderVO;
import com.macro.mall.portal.wxpay.domain.vo.RefundVO;
import com.macro.mall.portal.wxpay.enums.TradeTypeEnum;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.Element;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;

import java.math.BigDecimal;

@Slf4j
@AllArgsConstructor
@Component
public class WxpayHelper {

    private final MyWeChatPayUtil myWeChatPayUtil;


    /**
     * 微信H5页面支付
     *
     * @param createOrderVO
     * @return
     */
    @PostMapping("/wePay/h5")
    public JSONObject unifiedOrderHelper_H5(CreateOrderVO createOrderVO) {
        JSONObject res = new JSONObject();
        System.out.println(createOrderVO + "----------");
        String attach = createOrderVO.getAttachJson();
        String ip = createOrderVO.getIp();

        String orderNumber = createOrderVO.getOrderNumber();
        Integer totalFee = createOrderVO.getTotalFee();
        String body = createOrderVO.getBody();
//        String url = createOrderVO.getH5Url();
//        String urlName = createOrderVO.getUrlName();
        String openId = createOrderVO.getOpenId();
        String notifyUrl = createOrderVO.getNotifyUrl();

        try {
//            JSONObject sceneInfo = new JSONObject();
//            JSONObject h5_info = new JSONObject();
//            h5_info.put("type", "Wap");
//            h5_info.put("wap_url", url);
//            h5_info.put("wap_name", urlName);
//            sceneInfo.put("h5_info", h5_info);

            Document resXml = myWeChatPayUtil.unifiedOrder(attach, ip, orderNumber, body, totalFee, TradeTypeEnum.JSAPI, notifyUrl, openId);
            Element rootElement = resXml.getRootElement();
            log.info("看看H5支付统一下单响应：{}", rootElement.asXML());

            String returnCode = rootElement.element("return_code").getText();
            if ("SUCCESS".equals(returnCode)) {
                String resultCode = rootElement.element("result_code").getText();
                if ("SUCCESS".equals(resultCode)) {
                    // 统一下单成功
                    String appid = rootElement.element("appid").getText();
                    String partnerid = rootElement.element("mch_id").getText();// 商户id
                    String prepayid = rootElement.element("prepay_id").getText();// 预支付交易会话ID
//                    String mwebUrl = rootElement.element("mweb_url").getText();// h5地址

                    String noncestr = MyCodeUtil.getRandomStr(10, 32);// 随机字符串
                    String timestamp = System.currentTimeMillis() / 1000 + "";// 10位时间戳

                    // 返回调起支付所需数据
                    res.put("appId", appid);
                    // 扩展字段，固定值
//                    res.put("prepayid", "prepay_id="+prepayid);// 扩展字段，固定值
                    res.put("package", "prepay_id="+prepayid);
                    res.put("nonceStr", noncestr);
                    res.put("timeStamp", timestamp);
                    res.put("signType", "MD5");
//                    res.put("mweburl", mwebUrl);
                    String sign = myWeChatPayUtil.getSign(res);
                    res.put("partnerid", partnerid);
                    res.put("prepayid", "prepay_id="+prepayid);
//                    res.put("package", "Sign=WXPay");
                    res.put("sign", sign);// 参数签名
                } else {
                    res.put("msg", "下单失败：" + rootElement.asXML());
                }
            } else {
                res.put("msg", "下单失败：" + rootElement.asXML());
            }

        } catch (Exception e) {
            e.printStackTrace();
            res.put("msg", "下单失败：" + e.getMessage());
        }
        return res;
    }

    /**
     * 申请退款
     *
     * @param refundVO
     * @return
     */
    @PostMapping("/wePay/refund")
    public JSONObject refundHelper(RefundVO refundVO) {
        JSONObject res = new JSONObject();

        String orderId = refundVO.getOrderNumber();
        String refundId = refundVO.getRefundId();
        Integer totalFee = refundVO.getRefundMoney().multiply(new BigDecimal("100")).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
        String reason = refundVO.getReason();

        try {
            Document resXml = myWeChatPayUtil.refund(orderId, refundId, totalFee, reason);
            Element resRoot = resXml.getRootElement();

            String returnCode = resRoot.element("return_code").getText();
            if ("SUCCESS".equals(returnCode)) {
                String resultCode = resRoot.element("result_code").getText();
                if ("SUCCESS".equals(resultCode)) {
                    // 申请退款成功，若需要返回参数，可追加定义
                    res.put("msg", resultCode);
                } else if ("FAIL".equals(resultCode)) {
                    res.put("msg", "申请失败：" + resRoot.asXML());
                }

            } else {
                res.put("msg", "申请失败：" + resRoot.asXML());
            }

        } catch (Exception e) {
            res.put("msg", "申请失败：" + e.getMessage());
        }

        return res;
    }
}
